// 统一的网络请求方法
function request(params, isGetToken) {
  const globalData = getApp().globalData;
  const {curDept} = globalData;
  const {basePath} = globalData.config;
  // 不是在获取Token 并且 正在执行登录操作
  if (!isGetToken && globalData.isLogging) {
    globalData.requestQueue.push(params);
    return;
  }
  params.method = params.method.toUpperCase();
  if (params.method === 'GET' || params.dataType === 'query') {
    params.url = params.url + tansParams(params.data);
    params.data = {};
  }
  if (params.isLoading) {
    wx.showLoading({title: "加载中...",});
  }
  // 发起请求
  wx.request({
    url: basePath + params.url,
    data: params.data,
    header: {
      'app-id': wx.getAccountInfoSync().miniProgram.appId,
      Authorization: params.login ? undefined : "Bearer " + (wx.getStorageSync("token") || ""),
      'content-type': params.contentType || 'application/json',
      'dept-id': curDept?.value || '',
    },
    method: params.method || "POST",
    dataType: "json",
    responseType: params.responseType || "text",

    success: function (res) {
      handleResponse(res, params);
    },
    fail: function (err) {
      handleFail(err,params);
    },
  });
}

// 处理请求成功的响应
function handleResponse(res, params) {
  console.log('handleResponse', params, res)
  const {code, msg} = res.data;
  if (code === 200) {
    if (params.callBack) {
      params.callBack(res.data);
    }
  } else if (code === 401) {
    handleUnauthorized(params);
  } else if (code === 500) {
    wx.showToast({
      title: msg || '操作失败',
      icon: "none",
    });
  } else if (code === 400) {
    wx.showToast({
      title: msg || '操作失败',
      icon: "error",
    });
  } else {
    if (params.errCallBack) {
      params.errCallBack(res.data);
    }
  }
  hideLoading(params);
}

// 处理未授权的情况
function handleUnauthorized(params) {
  const globalData = getApp().globalData;
  if (globalData.isWxLogin) {
    getToken(params);
  } else {
    wx.navigateTo({
      url: "/pages/login/index",
    });
  }
}

// 处理请求失败
function handleFail(err,params) {
  hideLoading(params);
  wx.showToast({
    title: "服务器开小差了",
    icon: "error",
  });
}

// 隐藏加载提示
function hideLoading(params) {
  if (params.isLoading) {
    wx.hideLoading();
  }
}

// 通过code获取token,并保存到缓存
function getToken(params) {
  wx.showLoading({
    title: "登录中...",
  });
  const globalData = getApp().globalData;
  if (globalData.isLogging) {
    globalData.requestQueue.push(params);
    return;
  }
  globalData.isLogging = true;
  wx.login({
    success: (res) => {
      request({
        url: "/api/login/ma",
        method: "POST",
        data: {
          code: res.code,
        },
        callBack: (res) => {
          console.log('getToken', res)
          wx.setStorageSync("token", res.data);
          globalData.isLogging = false;
          globalData.token = res.data;
          globalData.isWxLogin = true;

          while (globalData.requestQueue.length) {
            request(globalData.requestQueue.pop());
          }

          wx.hideLoading();
          params && request(params);
          getUserInfo();
        },
      }, true)
    },
    fail: (err) => {
      wx.hideLoading();
      wx.showToast({
        title: "小程序授权失败",
        icon: "error",
      });
    },
  });
}

// 获取用户信息,并保存到缓存
function getUserInfo(callBack) {
  const globalData = getApp().globalData;
  request({
    url: `/api/um/getInfo`,
    method: "get",
    callBack:(res)=>{
      globalData.userInfo = res.data;
      callBack && callBack(res.data)
    },
  })
}

/**
 * 参数处理
 * @param {*} params  参数
 */
function tansParams(params) {
  if (!params) return '';
  let result = '?'
  for (const propName of Object.keys(params)) {
    const value = params[propName];
    var part = encodeURIComponent(propName) + "=";
    if (value !== null && value !== "" && typeof (value) !== "undefined") {
      if (typeof value === 'object') {
        for (const key of Object.keys(value)) {
          if (value[key] !== null && value[key] !== "" && typeof (value[key]) !== 'undefined') {
            let params = propName + '[' + key + ']';
            var subPart = encodeURIComponent(params) + "=";
            result += subPart + encodeURIComponent(value[key]) + "&";
          }
        }
      } else {
        result += part + encodeURIComponent(value) + "&";
      }
    }
  }
  return result.slice(0, -1)
}

module.exports = {
  request, getToken, getUserInfo
};